package com.hengtiansoft.lfy.adapter;

import android.content.Context;
import android.graphics.Color;
import android.icu.lang.UCharacter;
import android.text.Html;
import android.text.Layout;
import android.text.Selection;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.entity.EvaluatorMessageEntity;
import com.hengtiansoft.lfy.widget.CircleAnimView;
import com.hengtiansoft.lfy.widget.FreeChoiceTextView;

import java.util.List;

/**
 * Created by suyiyang on 2016/9/26.
 */

public class EvaluatorAdapter extends BaseAdapter {

    private List<EvaluatorMessageEntity> ev ;
    private Context context;
    private int currentPosition = 0;
    private EvaluatorAdapterListener evListener;
    //及格分数
    private int passScore = 75;
    private int goodScore = 90;
    private Holder mHolder;
    private boolean isAutoPlay = false;

    public EvaluatorAdapter(Context context, List<EvaluatorMessageEntity> ev, EvaluatorAdapterListener evListener){
        this.context = context;
        this.ev = ev;
        this.evListener = evListener;
    }
    @Override
    public int getCount() {
        return ev.size();
    }

    @Override
    public Object getItem(int position) {
        return ev.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder mHolder = null;
        if(convertView == null){
            mHolder = new Holder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.evaluator_item,parent,false);
            mHolder.iv_playEnglish = (ImageView) convertView.findViewById(R.id.iv_ea_playenglish);
            mHolder.iv_playReadVoice = (ImageView) convertView.findViewById(R.id.iv_ea_playreadvoice);
            mHolder.iv_score = (ImageView) convertView.findViewById(R.id.iv_ea_score);
            mHolder.iv_speak = (ImageView) convertView.findViewById(R.id.iv_ea_speak);
            mHolder.tv_chinese = (TextView) convertView.findViewById(R.id.tv_ea_chinese);
            mHolder.tv_english = (FreeChoiceTextView) convertView.findViewById(R.id.tv_ea_english);
            mHolder.tv_score = (TextView) convertView.findViewById(R.id.tv_ea_score);
            mHolder.lin_control = (LinearLayout) convertView.findViewById(R.id.lin_ea_control);

            mHolder.iv_stopEnglish = (CircleAnimView) convertView.findViewById(R.id.iv_ea_stopenglish);
            mHolder.iv_stopReadVoice = (CircleAnimView) convertView.findViewById(R.id.iv_ea_stopreadvoice);
            mHolder.iv_stopspeak = (CircleAnimView) convertView.findViewById(R.id.iv_ea_stopspeak);

            convertView.setTag(mHolder);
        }else{
            mHolder = (Holder) convertView.getTag();
        }
        mHolder.tv_english.setText(""+ev.get(position).getEnglish());
        mHolder.tv_chinese.setText(""+ev.get(position).getChinese());

        mHolder.tv_english.setTextColor(Color.BLACK);
//        mHolder.tv_chinese.setTextColor(Color.BLACK);

        //设置当前点击的item显示操作区域
        mHolder.lin_control.setVisibility(currentPosition == position ? View.VISIBLE: View.GONE);
        //显示分数
        if(ev.get(position).getScore() != null){
            mHolder.tv_score.setVisibility(View.VISIBLE);
            mHolder.iv_score.setVisibility(View.VISIBLE);
            int scor = Integer.parseInt(ev.get(position).getScore());
            mHolder.tv_english.setText(Html.fromHtml(getShowWord(ev.get(position).getEnglish(),ev.get(position).getWordscore())));
            if(scor < passScore){
//                mHolder.tv_english.setTextColor(Color.RED);
                mHolder.tv_score.setText("");
                mHolder.iv_score.setImageResource(R.drawable.icon_bad);
            }else{
//                mHolder.tv_english.setTextColor(Color.GREEN);
                mHolder.tv_score.setText(""+ev.get(position).getScore());
                mHolder.iv_score.setImageResource(R.drawable.icon_true);
            }

        }else{
            mHolder.tv_score.setVisibility(View.GONE);
            if("0".equals(ev.get(position).getState())){
                mHolder.iv_score.setVisibility(View.GONE);
            }else{
                mHolder.iv_score.setVisibility(View.VISIBLE);
                mHolder.iv_score.setImageResource(R.drawable.icon_bad);
            }
        }

        if(mHolder.lin_control.getVisibility() == View.VISIBLE && mHolder.iv_playReadVoice.getVisibility() == View.VISIBLE){
            if(ev.get(position).getLocalVoicePath() == null || "".equals(ev.get(position).getLocalVoicePath())){
                mHolder.iv_playReadVoice.setVisibility(View.GONE);
            }else
                mHolder.iv_playReadVoice.setVisibility(View.VISIBLE);

        }
        mHolder.iv_speak.setImageResource(R.drawable.btn_record2);
        mHolder.iv_playEnglish.setImageResource(R.drawable.btn_play);
        mHolder.iv_playReadVoice.setImageResource(R.drawable.btn_play2);

        mHolder.iv_speak.setOnClickListener(onClickListener);
        mHolder.iv_playEnglish.setOnClickListener(onClickListener);
        mHolder.iv_playReadVoice.setOnClickListener(onClickListener);

        mHolder.iv_stopspeak.setOnClickListener(onClickListener);
        mHolder.iv_stopEnglish.setOnClickListener(onClickListener);
        mHolder.iv_stopReadVoice.setOnClickListener(onClickListener);

        mHolder.tv_english.setOnTouchListener(touchListener);
        mHolder.tv_english.setTag(position);
        mHolder.iv_speak.setTag(position);

        mHolder.iv_playEnglish.setTag(position);
        mHolder.iv_playReadVoice.setTag(position);

        if(currentPosition == position){
            this.mHolder = mHolder;
            if(isAutoPlay) {
                mHolder.iv_playEnglish.performClick();
                isAutoPlay = false;
            }
        }
        return convertView;
    }

    /**
     * 设置可操作的Item
     */
    public void setCurrentPosition(int pos){
        currentPosition = pos;
        notifyDataSetChanged();
    }

    /**
     * 设置是否自动播放
     * @param isAutoPlay
     */
    public void setAutoPlay(boolean isAutoPlay){
        this.isAutoPlay = isAutoPlay;
    }

    /**
     * 切换模块
     * @param ev
     */
    public void refreshModeData(List<EvaluatorMessageEntity> ev){
        this.ev = ev;
        notifyDataSetChanged();
        currentPosition = 0;
    }

    /**
     * 处理单个单词的翻译
     */
    private int x = 0;
    private int y = 0;

    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(v.getId() == R.id.tv_ea_english){
                int pos = (int) v.getTag();
                if(pos == currentPosition){
                    switch (event.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            x = (int) event.getX();
                            y = (int) event.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:

                            break;
                        case MotionEvent.ACTION_UP:
                            if(Math.abs(event.getX() - x) > 30 || Math.abs(event.getY() - y) > 30){
                                return true;
                            }
                            Layout layout = ((FreeChoiceTextView)v).getLayout();
                            int line = layout.getLineForVertical((v.getScrollY()+ (int)event.getY()));
                            int off = layout.getOffsetForHorizontal(line, (int)event.getX());
                            Selection.setSelection(((FreeChoiceTextView)v).getEditableText(), off);
                            int index = ((FreeChoiceTextView)v).getSelectionStart();
                            String str = ((FreeChoiceTextView)v).getText().toString();
                            str = str.replace(","," ");
                            int start = str.lastIndexOf(" ",index);
                            if(start < 0)
                                start = 0;
                            int end = str.indexOf(" ",start);
                            if(end <= start + 1 || start + 1 < str.length()){
                                end = str.indexOf(" ",start + 1);
                            }
                            if(end < 0 || end > str.length()){
                                end = str.length();
                            }
                            if(start > end)
                                start = 0;
//                            Log.d("tag","start = "+start+" end = "+end);
                            String s = str.substring(start,end);
                            if(evListener != null){
                                evListener.transWord(s);
                            }
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            break;
                        case MotionEvent.ACTION_OUTSIDE:
                            break;
                    }
                    return true;
                }else{
                    if(event.getAction() == MotionEvent.ACTION_UP){
                        if(evListener != null){
                            evListener.clickItem((int)v.getTag());
                        }
                    }
                }
            }
            return false;
        }
    };
    /**
     * 处理单击事件
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.iv_ea_speak:

                    evListener.clearWorking();

                    changeImageResource(v);
                    String english = ev.get(currentPosition).getEnglish();
                    evListener.speak(english);
                    break;
                case R.id.iv_ea_playenglish:

                    evListener.clearWorking();

                    changeImageResource(v);
                    String en = ev.get(currentPosition).getEnglish();
                    evListener.playEnglish(en);
                    break;
                case R.id.iv_ea_playreadvoice:

                    evListener.clearWorking();

                    changeImageResource(v);
                    String path = ev.get(currentPosition).getLocalVoicePath();
                    evListener.playVoice(path);
                    break;
                case R.id.iv_ea_stopspeak:
                    resetImageResource();
                    evListener.stopspeak();
                    break;
                case R.id.iv_ea_stopenglish:
                    resetImageResource();
                    evListener.stopEnglish();
                    break;
                case R.id.iv_ea_stopreadvoice:
                    resetImageResource();
                    evListener.stopVoice();
                    break;
            }
        }
    };

    /**
     * 改变按键状态
     * @param v
     */
    public void changeImageResource(View v){
        if(mHolder != null){
            if(v.getId() == mHolder.iv_speak.getId()){
                mHolder.iv_stopspeak.setVisibility(View.VISIBLE);
                mHolder.iv_speak.setVisibility(View.GONE);
            }else if(v.getId() == mHolder.iv_playEnglish.getId()){
                mHolder.iv_stopEnglish.setVisibility(View.VISIBLE);
                mHolder.iv_playEnglish.setVisibility(View.GONE);
            }else if(v.getId() == mHolder.iv_playReadVoice.getId()){
                mHolder.iv_stopReadVoice.setVisibility(View.VISIBLE);
                mHolder.iv_playReadVoice.setVisibility(View.GONE);
            }
            notifyDataSetChanged();
        }
    }
    /**
     * 恢复按键
     */
    public void resetImageResource(){
        if(this.mHolder != null){
            mHolder.iv_playEnglish.setVisibility(View.VISIBLE);
            mHolder.iv_stopEnglish.setVisibility(View.GONE);

            mHolder.iv_speak.setVisibility(View.VISIBLE);
            mHolder.iv_stopspeak.setVisibility(View.GONE);

            int pos = (int) mHolder.iv_playReadVoice.getTag();
            if(pos < ev.size()){
                if(ev.get(pos).getLocalVoicePath() != null){
                    mHolder.iv_playReadVoice.setVisibility(View.VISIBLE);
                    mHolder.iv_stopReadVoice.setVisibility(View.GONE);
                }else {
                    mHolder.iv_playReadVoice.setVisibility(View.GONE);
                    mHolder.iv_stopReadVoice.setVisibility(View.GONE);
                }
            }else{
                mHolder.iv_playReadVoice.setVisibility(View.GONE);
                mHolder.iv_stopReadVoice.setVisibility(View.GONE);
            }

            notifyDataSetChanged();
        }
    }
    private static class  Holder{
        public FreeChoiceTextView tv_english;
        public TextView tv_chinese;
        public TextView tv_score;
        public LinearLayout lin_control;
        public ImageView iv_playEnglish;
        public ImageView iv_playReadVoice;
        public ImageView iv_speak;

        public CircleAnimView iv_stopEnglish;
        public CircleAnimView iv_stopReadVoice;
        public CircleAnimView iv_stopspeak;

        public ImageView iv_score;
    }
    public interface EvaluatorAdapterListener{
        public void speak(String str);
        public void playEnglish(String english);
        public void playVoice(String chinese);
        public void stopspeak();
        public void stopEnglish();
        public void stopVoice();
        public void transWord(String string);
        public void clickItem(int pos);
        public void clearWorking();
    }

    /**
     * 获取多颜色文本信息
     * @param str
     * @param split
     * @return
     */
    private String getShowWord(String str, String split){
        String fontStart = "<font color=" + context.getResources().getColor(R.color.wrong_red) + ">";
        String fontEnd = "</font>";

        String fontStart2 = "<font color=" +context.getResources().getColor(R.color.right_green) + ">";
        String fontEnd2 = "</font>";

        StringBuffer sb = new StringBuffer();
        str.replace(","," , ");
        str.replace("."," . ");
        str.replace("  "," ");
        String[] originalStr = str.split(" ");
        String[] scores = split.split(" ");
        int index = 0;
        for(int i = 0 ; i < originalStr.length ; i ++){
            if(!",".equals(originalStr[i]) && !".".equals(originalStr[i]) && !" ".equals(originalStr[i])){
//                Log.d("tag","originalStr[i] = "+originalStr[i]);
                int score = passScore + 1;
                if(index < scores.length)
                    score = Integer.parseInt(scores[index]);
                index ++ ;
                //不及格
                if(score < passScore){
                    sb.append((fontStart + originalStr[i] + fontEnd)+" ");

                }else if(score >= goodScore){

                    sb.append((fontStart2 + originalStr[i] + fontEnd2)+" ");

                } else{
                    sb.append(originalStr[i] + " ");
                }
            }else{
                sb.append(originalStr[i] + " ");
            }
        }
        return sb.toString();
    }
}
